package com.example.socket;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btn;
    private EditText et_send;
    private EditText et_accept;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn = findViewById(R.id.btn_submit);
        et_send = findViewById(R.id.ed_tinput);
        et_accept = findViewById(R.id.ed_accept);

        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Socket socket = new Socket("192.168.3.42",12345);
                    OutputStream os = socket.getOutputStream();
                    os.write(et_send.getText().toString().getBytes());
                    os.flush();
                    socket.shutdownOutput();

                    InputStream is = socket.getInputStream();
                    InputStreamReader reader = new InputStreamReader(is);
                    BufferedReader bufferedReader = new BufferedReader(reader);
                    String s = null;
                    final StringBuffer sb = new StringBuffer();
                    while ((s = bufferedReader.readLine())!= null){
                        sb.append(s);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            et_accept.setText(sb.toString());
                        }
                    });
                    bufferedReader.close();
                    reader.close();
                    is.close();
                    os.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}